package test.src.awt_swing;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class FileChooserDemo {
    JFrame jf = new JFrame("这里测试FileChooser");
    JFileChooser jFileChooser = new JFileChooser();

    BufferedImage image;

    JMenuBar jMenuBar = new JMenuBar();
    JMenu fileMenu = new JMenu("文件");

    JMenuItem open = new JMenuItem(new AbstractAction("打开") {
        @Override
        public void actionPerformed(ActionEvent e) {
            jFileChooser.showOpenDialog(jf);
            File file = jFileChooser.getSelectedFile();
            try {
                image = ImageIO.read(file);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    JMenuItem save = new JMenuItem(new AbstractAction("保存") {
        @Override
        public void actionPerformed(ActionEvent e) {
            jFileChooser.showSaveDialog(jf);
            File file = jFileChooser.getSelectedFile();
            try {
                ImageIO.write(image, "jpeg", file);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    private class MyCanvas extends JPanel {
        @Override
        public void paint(Graphics g) {
            g.drawImage(image, 0, 0, null);
        }
    }

    MyCanvas drawArea = new MyCanvas();

    public void init() {
        fileMenu.add(open);
        fileMenu.add(save);
        jMenuBar.add(fileMenu);
        jf.setJMenuBar(jMenuBar);

        drawArea.setPreferredSize(new Dimension(1080, 720));
        jf.add(drawArea);

        jf.pack();
        jf.setVisible(true);
    }

    public static void main(String[] args) {
        new FileChooserDemo().init();
    }
}